<?php
class Delivery_Model_Collection_Abstract
	extends ArrayObject
{
	protected $_elements = array();
	public static $sortKey;
	
	public function __construct( )
	{
		parent::__construct( $this->_elements );
	}
	
	public function append( $object ){
		$this[$object->getId()] = $object;
	}
	
	public function getByKey( $key, $value)
	{
		$className = get_called_class();
		
		$collection = new $className;
		
		if ( is_array( $value )){
    		
		    foreach ($this as $element) {
    			if ( in_array( $element->$key, $value )){
    				$collection->append( $element ) ;
    			}
    		}
    		
		} else {
    		
		    foreach ($this as $element) {
    			if ($element->$key == $value){
    				$collection->append( $element ) ;
    			}
    		}
    		
		}
		
		return $collection;
	}
	
	public function getIds()
	{
		$ids = array();
		
		foreach ($this as $element) {
			$ids[] = $element->getId();
		}
		
		return $ids;
	}
	
	public function getKeyValues( $name, $unique = false, $ignoreNull = false )
	{
		$values = array();
		
		foreach ($this as $element) {
			
			$val = $element->$name;
			
			if ( $ignoreNull && is_null($val)){
				continue;
			}
			
			$values[] = $val;
		}
		
		if ( $unique ){
			$values = array_unique( $values );
		}
		
		return $values;
	}
	
	public static function sorter( $a, $b )
    {
        return strcasecmp( $a->{self::$sortKey}, $b->{self::$sortKey} );
    }

    public function sortByProp( $prop, $values = null )
    {
        self::$sortKey = $prop;
        
        if ( !is_null($values)){
        
        	if ( ! is_array($values)){
        		$values = explode(",",$values);
        	}
        	
        	$class = get_class($this);
        	$newCollection = new $class;
        	
        	foreach ($values as $value){
        		
        		$items = $this->getByKey($prop, trim($value));
        		
        		foreach ($items as &$item){
        			$newCollection->append( $item );
        			unset($item);
        		}
        	}
        	
        	foreach ($this as $item){
        		$newCollection->append( $item );
        	}
        	
        	$this->exchangeArray( $newCollection->getArrayCopy());
        	
        	
        	
        } 
        else {
        	$this->uasort(array( $this, 'sorter' ));
        }
    }
	
}